package com.example.sjh_web.other

import android.content.Context
import android.os.Environment
import android.text.Layout
import android.util.Log
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import java.io.File
import java.io.FileOutputStream


class sjh_SDFileHelper {
    private var context: Context? = null

    constructor() {}
    constructor(context: Context?) : super() {
        this.context = context
    }

    //Glide保存图片
    fun savePicture(fileName: String, url: String?) {
        Glide.with(context).load(url).asBitmap().toBytes()
            .into(object : SimpleTarget<ByteArray?>() {
                override fun onResourceReady(
                        resource: ByteArray?,
                        glideAnimation: GlideAnimation<in ByteArray?>?
                ) {
                    try {
                        savaFileToSD(fileName, resource)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            })
    }

    //往SD卡写入文件的方法
    @Throws(Exception::class)
    fun savaFileToSD(filename: String, bytes: ByteArray?) {
        //如果手机已插入sd卡,且app具有读写sd卡的权限
        var filename = filename
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            val filePath: String =
                Environment.getExternalStorageDirectory().getCanonicalPath().toString() + "/Pictures/my_web"
//            Log.d("filePath", filePath)
            val dir1 = File(filePath)
            if (!dir1.exists()) {
                dir1.mkdirs()
            }
            filename = "$filePath/$filename"
            val output = FileOutputStream(filename)
            output.write(bytes)
            //将bytes写入到输出流中
            output.close()
            //关闭输出流
            Toast.makeText(context, "图片已成功保存到$filePath", Toast.LENGTH_SHORT).show()

        } else Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show()
    }

    fun getPicNameFromPath(picturePath: String): String? {
        val temp = picturePath.replace("\\\\".toRegex(), "/").split("/".toRegex()).toTypedArray()
        var fileName = ""
        if (temp.size > 1) {
            fileName = temp[temp.size - 1]
        }
        return fileName
    }

}